﻿using CGT.GOP.App_Start;
using CGT.GOP.Common;
using CGT.GOP.Models.User;
using CGT.Infrastructure.Entity;
using CGT.Infrastructure.Repository;
using CGT.Infrastructure.Service;
using Dapper;
using Dapper.Extensions;
using OF.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.ModelBinding;
using System.Web.Mvc;

namespace CGT.GOP.Controllers
{
    public class UserController : BaseController
    {

        GovLogSafeService lsService = new GovLogSafeService();  //安全日志
        GovLogOperateService laService = new GovLogOperateService();//行为日志
        GovUserService Service = new GovUserService();
        GovRoleService roleService = new GovRoleService();
        protected GovUserRepository repository;

        #region 视图
        /// <summary>
        /// 用户管理首页
        /// </summary>
        /// <returns></returns>
        [Authentication(MenuCode = 10101)]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 用户列表分部视图
        /// </summary>
        /// <returns></returns>
        [Authentication(MenuCode = 10101)]
        public PartialViewResult ParUserList()
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<GovUser> page = Service.GetPages(pageIndex, pageSize);
            List<GovUser> list = page.rows;
            ViewBag.OutCount = page.total;
            return PartialView(list);
        }

        /// <summary>
        /// 编辑用户页面
        /// </summary>
        /// <returns></returns>
        [Authentication(MenuCode = 10101)]
        public ActionResult EditUser()
        {
            ViewBag.RoleList = new List<GovRole>();
            ViewBag.UserInfo = new GovUser();

            var list = roleService.QueryAll();
            ViewBag.RoleList = list.Where(a => a.IsActive == 1).ToList();
            var id = EConvert.ToInt(GetParam("id"));
            #region 日志
            var log = new GovLogOperate()
            {
                CreatedDate = DateTime.Now,
                Description = this.CurrentUser.UserName + "添加用户",
                Incident = "访问页面",
                IncidentType = 4,
                Result = "",
                ModuleId = 10101,
                UserId = this.CurrentUser.UserId//当前登录人ID
            };
            var logsafe = new GovLogSafe()
            {
                CreatedDate = DateTime.Now,
                Description = this.CurrentUser.UserName + "添加用户",
                Incident = "访问页面",
                IncidentType = 4,
                Result = "",
                ModuleId = 10101,
                UserId = this.CurrentUser.UserId//当前登录人ID
            };
            #endregion
            if (id > 0)
            {
                log.Description = this.CurrentUser.UserName + "编辑修改用户";
                logsafe.Description = this.CurrentUser.UserName + "编辑修改用户";
                var userInfo = Service.Single(id);
                ViewBag.UserInfo = userInfo;
            }
            lsService.Insert(logsafe);
            laService.Insert(log);
            return View();
        }

        /// <summary>
        /// 配置用户城市
        /// </summary>
        /// <returns></returns>
        [Authentication(MenuCode = 10101)]
        public ActionResult ConfigUserCities()
        {
            var userId = EConvert.ToInt(GetParam("id"));
            var list = new GovUserCitiesRelService().GetByUserId(userId);
            //拼接模版id，逗号间隔
            var tplStr = "";
            if (list.Count() > 0)
                tplStr = list.Aggregate("", (strs, tpl) => strs + tpl.CityId.ToString() + ",");
            if (!string.IsNullOrWhiteSpace(tplStr))
                tplStr = tplStr.Substring(0, tplStr.Length - 1);
            ViewBag.UserId = userId;
            ViewBag.Cities = tplStr;
            return View();
        }

        /// <summary>
        ///  保存用户关联的城市
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ContentResult UserCitiesSave(string SelCitiesStr, string UserId)
        {
            var res = new ResultData<string>();
            var str = SelCitiesStr;//拿到的字符串格式是 pid|cid,pid2|cid2
            var userId = EConvert.ToInt(UserId);

            if (string.IsNullOrWhiteSpace(str))
            {
                res.status = -1;
                res.message = "未选择城市，如不需要配置城市，请直接关闭页面即可";
                return ReturnResult(res);
            }
            else
            {
                try
                {
                    var cityArr = HttpUtility.UrlDecode(str).Split(',');
                    var citys = new List<GovUserCitiesRel>();
                    foreach (var pcid in cityArr)
                    {
                        var pcArr = pcid.Split('-');//分割一下省份id和城市id

                        var cityEntity = new GovUserCitiesRel()
                        {
                            ProvinceId = EConvert.ToInt(pcArr[0]),
                            CityId = EConvert.ToInt(pcArr[1]),
                            UserId = userId,
                            Remark = "",
                        };
                        citys.Add(cityEntity);
                    }
                    var service_city = new GovUserCitiesRelService();
                    //先批量删除，再批量插入
                    service_city.BatchDelete(userId);
                    service_city.Insert(citys);
                }
                catch (Exception ex)
                {
                    res.status = -1;
                    res.message = "保存失败，未选择城市，如不需要配置城市，请直接关闭页面即可";
                    return ReturnResult(res);
                }
            }
            return ReturnResult(res);

        }

        /// <summary>
        /// 更新用户密码
        /// </summary>
        /// <returns></returns>
        [Authentication(MenuCode = 10101)]
        public ActionResult EditPassword()
        {
            ViewBag.UserID = GetParam("id");
            return View();
        }

        /// <summary>
        /// 无效用户管理
        /// </summary>
        /// <returns></returns>
        [Authentication(MenuCode = 10107)]
        public ActionResult InvalidUserManage()
        {
            return View();
        }

        /// <summary>
        /// 无效用户分部视图
        /// </summary>
        /// <returns></returns>
        [Authentication(MenuCode = 10107)]
        public PartialViewResult ParInvalidUserList()
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            var state = (short)2;//查询无效用户为2，正常是1
            var realName = GetParam("realName");
            var loginName = GetParam("loginName");
            Page<GovUser> page = Service.GetPages(pageIndex, pageSize, state, realName, loginName);
            List<GovUser> list = page.rows;
            ViewBag.OutCount = page.total;
            return PartialView(list);
        }

        #endregion

        #region 操作方法
        /// <summary>
        /// 保存用户
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SaveUser(GovUser info)
        {
            var res = new ResultData<string>();
            info.UpdateTime = DateTime.Now;
            if (string.IsNullOrWhiteSpace(info.AllowIP))
                info.AllowIP = "*";
            info.CurrentLoginIP = "";
            info.ForceChangePwd = 2;//只有激活时需要重新强制修改密码
            info.IsActive = 1;
            info.LastLoginIP = "";

            if (DateTime.Now > info.UserExpireDate || DateTime.Now > info.PasswordExpireDate)
                info.State = 2;
            else
                info.State = 1;

            //只有添加时处理密码
            if (info.UserID <= 0)
            {
                var pwd = info.UserName + info.PassWord + "!!!";
                info.PassWord = MD5Helper.MD5String(pwd);
                info.LastLoginTime = DateTimeHelper.MinDateTime();
                info.CurrentLoginTime = DateTimeHelper.MinDateTime();
                info.CreateDateTime = DateTime.Now;
            }
            else
            {
                var user = Service.Single(info.UserID);
                info.LastLoginTime = user.LastLoginTime;
                info.CurrentLoginTime = user.CurrentLoginTime;
                info.CreateDateTime = user.CreateDateTime;
                info.PassWord = user.PassWord;
                info.LastLoginIP = user.LastLoginIP;
                info.CurrentLoginIP = user.CurrentLoginIP;
            }
            info.CheckCode = "";

            bool isExist = Service.CheckUserNumIsExist(info.UserNumber, info.IsPolice, info.UserID);
            if (isExist)
            {
                res.message = "员工/警员编号已经存在";
                res.status = -1;
                return ReturnResult(res);
            }
            isExist = Service.CheckIdentityCodeIsExist(info.IdentityCode, info.UserID);
            if (isExist)
            {
                res.message = "身份证明号码已经存在";
                res.status = -1;
                return ReturnResult(res);
            }
            isExist = Service.CheckLoginNameIsExist(info.UserName, info.UserID);
            if (isExist)
            {
                res.message = "登录帐号已经存在";
                res.status = -1;
                return ReturnResult(res);
            }

            var log = new GovLogOperate()
            {
                CreatedDate = DateTime.Now,
                Description = this.CurrentUser.UserName + "添加用户",
                Incident = "保存用户",
                IncidentType = 3,
                Result = "",
                ModuleId = 10101,
                UserId = this.CurrentUser.UserId//当前登录人ID
            };

            var safelog = new GovLogSafe
            {
                CreatedDate = DateTime.Now,
                Description = this.CurrentUser.UserName + "添加用户",
                Incident = "访问页面",
                IncidentType = 3,
                Result = "",
                ModuleId = 10101,
                UserId = this.CurrentUser.UserId//当前登录人ID
            };

            if (info.UserID > 0)
            {
                log.Description = this.CurrentUser.UserName + "修改用户";
                safelog.Description = this.CurrentUser.UserName + "修改用户";
            }
            try
            {
                var id = 0;
                if (info.UserID <= 0)
                {
                    Service.Insert(info);
                    id = info.UserID;
                }
                else
                {
                    Service.Update(info);
                    id = info.UserID;
                }
                log.Result = "成功,返回ID:" + id;
                safelog.Result = "成功,返回ID:" + id;
            }
            catch (Exception ex)
            {
                res.message = "添加失败";
                res.status = -1;
                log.Result = "失败,异常信息：" + ex.Message;
                safelog.Result = "失败,异常信息：" + ex.Message;
            }
            finally
            {
                laService.Insert(log);
                lsService.Insert(safelog);
            }
            return ReturnResult(res);
        }

        /// <summary>
        /// 激活用户
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult ActivateUser(int id)
        {
            var res = new ResultData<string>();
            var erroruService = new GovLoginErrorRecordUserService();//用户错误记录service
            var blackuService = new GovBlackListUserService();//黑名单用户service           
            try
            {
                //清空用户错误记录表错误次数
                var rUser = erroruService.GetByUser(id);
                if (rUser != null && rUser.RecordID > 0)
                {
                    rUser.ErrorCount = 0;
                    erroruService.Update(rUser);
                }

                //从黑名单中删除用户黑名单信息
                var blackUser = blackuService.GetByUser(id);
                if (blackUser != null && blackUser.ID > 0)
                {
                    blackuService.Delete(blackUser.ID);
                }

                //更新用户信息，如果用户过期则续期一年
                var userinfo = Service.Single(id);
                if (userinfo.PasswordExpireDate < DateTime.Now)
                    userinfo.PasswordExpireDate = DateTime.Now.AddYears(1);
                if (userinfo.UserExpireDate < DateTime.Now)
                    userinfo.UserExpireDate = DateTime.Now.AddYears(1);

                userinfo.State = 1;
                userinfo.ForceChangePwd = 1;//激活用户强制修改密码
                userinfo.CheckCode = "";
                Service.Update(userinfo);
            }
            catch (Exception ex)
            {
                res.message = "激活失败,请重试";
                res.status = -1;
            }
            try
            {
                //操作日志
                laService.Insert(new GovLogOperate()
                {
                    CreatedDate = DateTime.Now,
                    Description = "快速激活用户，包含清空错误次数、移除黑名单，过期用户自动续期1年; 用户id：" + id,
                    Incident = "无效用户管理",
                    IncidentType = 3,
                    Result = "快速激活解锁用户",
                    ModuleId = 10108
                });
            }
            catch (Exception ex) { }
            return ReturnResult(res);
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult DeleteUser(int id)
        {
            var res = ResultData<string>.Success();
            if (id <= 0)
            {
                res.status = -1;
                res.message = "操作失败！缺少必须的参数UserId";
            }
            try
            {
                var model = Service.Single(id);
                if (model != null)
                {
                    model.UpdateTime = DateTime.Now;
                    model.IsActive = 0;
                }
                Service.Update(model);
            }
            catch (Exception ex)
            {
                res.status = -1;
                res.message = "操作失败！" + ex.Message;
            }
            return ReturnResult(res);
        }

        /// <summary>
        /// 批量删除用户
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult BatchDeleteUser(string ids)
        {
            var res = new ResultData<string>();
            if (string.IsNullOrWhiteSpace(ids))
            {
                res.status = -1;
                res.message = "操作失败！缺少必须的参数ids";
            }
            try
            {
                Service.BatchLogicDelete(ids);
            }
            catch (Exception ex)
            {
                res.status = -1;
                res.message = "操作失败！" + ex.Message;
            }
            return ReturnResult(res);
        }

        [HttpPost]
        public ContentResult EditPasswordSave(PwdEditModel model)
        {
            //参数错误 lsc 2019-01-25
            var res = new ResultData<string>();
            var userInfo = Service.Single(model.UserId);
            if (userInfo != null)
            {
                var md5Pwd = MD5Helper.MD5String(userInfo.UserName + model.NewPwd + "!!!");
                userInfo.PassWord = md5Pwd;
                userInfo.UpdateTime = DateTime.Now;
                try
                {
                    Service.Update(userInfo);
                }
                catch (Exception ex)
                {
                    res.status = -1;
                    res.message = "操作失败！" + ex.Message;
                }
            }
            return ReturnResult(res);
        }

        /// <summary>
        /// 保存安全日志
        /// </summary>
        [AllowAnonymous]
        private void SafeLogging(string currentCheckCode, string code, int userId)
        {

        }

        #endregion

        #region 验证
        /// <summary>
        ///  验证编号是否存在
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public ContentResult IsExistNo()
        {
            var res = ResultData<string>.Success();

            var num = GetParam("userNumber");
            var isPolice = EConvert.ToShort(GetParam("isPolice"));
            var userId = EConvert.ToInt(GetParam("userId"));
            try
            {
                var isExist = Service.CheckUserNumIsExist(num, isPolice, userId);
                res.data = isExist ? "1" : "0"; //1为已经存在，0为不存在
            }
            catch (Exception ex)
            {
                res.status = -1;
                res.message = "发生异常";
                res.data = "0";
                return ReturnResult(res);
            }
            return ReturnResult(res);
        }

        /// <summary>
        ///  验证登录名是否已经存在
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public ContentResult IsExistLoginName()
        {
            var res = ResultData<string>.Success();
            var loginName = GetParam("loginName");
            var userId = EConvert.ToInt(GetParam("userId"));
            try
            {
                var isExist = Service.CheckLoginNameIsExist(loginName, userId);
                res.data = isExist ? "1" : "0"; //1为已经存在，0为不存在
            }
            catch (Exception ex)
            {
                res.status = -1;
                res.message = "发生异常";
                res.data = "0";
                return ReturnResult(res);
            }
            return ReturnResult(res);
        }

        /// <summary>
        ///  验证身份证号码是否已经存在
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public ContentResult IsExistIdNum()
        {
            var res = ResultData<string>.Success();
            var IdentityCode = GetParam("idnum");
            var userId = EConvert.ToInt(GetParam("userId"));
            try
            {
                var isExist = Service.CheckIdentityCodeIsExist(IdentityCode, userId);
                res.data = isExist ? "1" : "0"; //1为已经存在，0为不存在
            }
            catch (Exception ex)
            {
                res.status = -1;
                res.message = "发生异常";
                res.data = "0";
                return ReturnResult(res);
            }
            return ReturnResult(res);
        }

        #endregion
    }
}